import { ref, computed } from "vue";
import { defineStore } from "pinia";
import { storage } from "@/utils/storage";
import api from "@/api";
import _ from "lodash";
interface UserInfoType {
  name: string;
  role_id: number;
  zone_id: number;
}

interface NavCfgType {
  selectedKeys: string[];
  openKeys: string[];
  preOpenKeys: string[];
  collapsed: boolean;
}

interface SelectType {
  catLevel: number;
  cid: number;
  gmtCreated: string;
  gmtModified: null;
  leaf: Boolean;
  name: string;
  parentId: number;
  platform: string;
}

const DEFAULT_USER_INFO = {
  name: "",
  role_id: 0,
  zone_id: 0,
};

const DEFAULT_NAV_CFG = {
  selectedKeys: [""],
  openKeys: [""],
  preOpenKeys: [""],
  collapsed: false,
};

const DEFAULT_TYPE = [
  {
    catLevel: 0,
    cid: 0,
    gmtCreated: "",
    gmtModified: null,
    leaf: false,
    name: "全部",
    parentId: 0,
    platform: "",
  },
];

export const useMainStore = defineStore("main", () => {
  const user_info = ref<UserInfoType>({ ...DEFAULT_USER_INFO }); // 个人信息
  const nav_cfg = ref<string | NavCfgType>(
    storage.get<NavCfgType>("nav_cfg") || DEFAULT_NAV_CFG
  );
  const category_list = ref<SelectType[]>(DEFAULT_TYPE);
  const token = ref(storage.get<string>("token") || "");
  const setToken = (data: string) => {
    token.value = data;
    storage.set("token", data);
  };
  const isLogin = computed(() => Boolean(token.value));

  const logout = () => {
    token.value = "";
    user_info.value = { ...DEFAULT_USER_INFO };
    storage.remove("userInfo");
    storage.remove("token");
  };

  const getUserInfo = () => {
    return api.getUserInfo().then((res: any) => {
      if (res.code == 0) {
        setUserInfo(res.data);
      }
    });
  };

  const getCategoryList = () => {
    return api.getCategoryList().then((res: any) => {
      if (res.code == "200") {
        setCategoryList(res.data);
      }
    });
  };

  const setUserInfo = (info: UserInfoType) => {
    user_info.value = info;
    storage.set("userInfo", info);
  };

  const setCategoryList = (list: SelectType[]) => {
    category_list.value = category_list.value.concat(list);
    storage.set("categoryList", category_list.value);
  };

  const setNavKey = (key: string, parent: string) => {
    if (!nav_cfg.value.openKeys.includes(parent)) {
      nav_cfg.value.openKeys.push(parent);
    }
    nav_cfg.value.selectedKeys = [key];
    setNavCfg();
  };

  const setNavCfg = () => {
    storage.set("nav_cfg", nav_cfg.value);
  };
  return {
    nav_cfg,
    token,
    isLogin,
    setToken,
    getUserInfo,
    user_info,
    setUserInfo,
    logout,
    setNavCfg,
    setNavKey,
    category_list,
    getCategoryList,
  };
});
